<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h2>首页概览</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="date-picker"
          @change="handleDateRangeChange"
        />
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-title">用户总数</div>
            <div class="stat-value">{{ stats.userCount }}</div>
            <div class="stat-change" :class="{ positive: stats.userGrowth > 0, negative: stats.userGrowth < 0 }">
              <span>{{ stats.userGrowth > 0 ? '+' : '' }}{{ stats.userGrowth }}%</span>
              <span class="change-label">较上月</span>
            </div>
          </div>
          <div class="stat-icon user-icon">
            <el-icon><User /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-title">角色总数</div>
            <div class="stat-value">{{ stats.roleCount }}</div>
            <div class="stat-change" :class="{ positive: stats.roleGrowth > 0, negative: stats.roleGrowth < 0 }">
              <span>{{ stats.roleGrowth > 0 ? '+' : '' }}{{ stats.roleGrowth }}%</span>
              <span class="change-label">较上月</span>
            </div>
          </div>
          <div class="stat-icon role-icon">
            <el-icon><Avatar /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-title">权限总数</div>
            <div class="stat-value">{{ stats.permissionCount }}</div>
            <div class="stat-change" :class="{ positive: stats.permissionGrowth > 0, negative: stats.permissionGrowth < 0 }">
              <span>{{ stats.permissionGrowth > 0 ? '+' : '' }}{{ stats.permissionGrowth }}%</span>
              <span class="change-label">较上月</span>
            </div>
          </div>
          <div class="stat-icon permission-icon">
            <el-icon><Lock /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-title">今日操作</div>
            <div class="stat-value">{{ stats.todayOperations }}</div>
            <div class="stat-change" :class="{ positive: stats.operationTrend > 0, negative: stats.operationTrend < 0 }">
              <span>{{ stats.operationTrend > 0 ? '+' : '' }}{{ stats.operationTrend }}%</span>
              <span class="change-label">较昨日</span>
            </div>
          </div>
          <div class="stat-icon operation-icon">
            <el-icon><Operation /></el-icon>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>用户增长趋势</span>
          </div>
        </template>
        <div class="chart-content">
          <div ref="userGrowthChart" class="chart"></div>
        </div>
      </el-card>

      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>操作类型分布</span>
          </div>
        </template>
        <div class="chart-content">
          <div ref="operationTypeChart" class="chart"></div>
        </div>
      </el-card>
    </div>

    <!-- 最近操作记录 -->
    <el-card class="recent-operations-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>最近操作记录</span>
          <el-link type="primary" @click="viewAllOperations">查看全部</el-link>
        </div>
      </template>
      <el-table :data="recentOperations" style="width: 100%">
        <el-table-column prop="operationTime" label="操作时间" width="180" />
        <el-table-column prop="operatorName" label="操作人" width="120" />
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="scope">
            <el-tag :type="getOperationTypeTag(scope.row.operationType)">
              {{ scope.row.operationType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="entityName" label="操作实体" width="120" />
        <el-table-column prop="description" label="操作描述" show-overflow-tooltip />
        <el-table-column prop="ipAddress" label="IP地址" width="150" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  name: 'Dashboard',
  setup() {
    // 日期范围
    const dateRange = ref([])
    
    // 统计数据
    const stats = reactive({
      userCount: 0,
      roleCount: 0,
      permissionCount: 0,
      todayOperations: 0,
      userGrowth: 0,
      roleGrowth: 0,
      permissionGrowth: 0,
      operationTrend: 0
    })
    
    // 最近操作记录
    const recentOperations = ref([])
    
    // 图表实例
    const userGrowthChart = ref(null)
    const operationTypeChart = ref(null)
    let userGrowthChartInstance = null
    let operationTypeChartInstance = null
    
    // 处理日期范围变化
    const handleDateRangeChange = (range) => {
      if (range) {
        loadDashboardData()
      }
    }
    
    // 刷新数据
    const refreshData = () => {
      loadDashboardData()
    }
    
    // 查看全部操作记录
    const viewAllOperations = () => {
      // 跳转到审计日志页面
      window.location.href = '/#/system/audit'
    }
    
    // 获取操作类型标签样式
    const getOperationTypeTag = (operationType) => {
      switch (operationType) {
        case 'INSERT':
          return 'success'
        case 'UPDATE':
          return 'primary'
        case 'DELETE':
          return 'danger'
        default:
          return 'info'
      }
    }
    
    // 加载仪表盘数据
    const loadDashboardData = async () => {
      try {
        // 这里应该调用后端API获取真实数据
        // 由于是模拟环境，我们使用mock数据
        
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // Mock统计数据
        stats.userCount = 128
        stats.roleCount = 12
        stats.permissionCount = 86
        stats.todayOperations = 256
        stats.userGrowth = 12.5
        stats.roleGrowth = 5.0
        stats.permissionGrowth = 8.3
        stats.operationTrend = -3.2
        
        // Mock最近操作记录
        recentOperations.value = [
          {
            operationTime: '2025-09-10 10:25:36',
            operatorName: '张三',
            operationType: 'UPDATE',
            entityName: '用户',
            description: '更新用户信息',
            ipAddress: '192.168.1.100'
          },
          {
            operationTime: '2025-09-10 09:42:18',
            operatorName: '李四',
            operationType: 'INSERT',
            entityName: '角色',
            description: '创建新角色',
            ipAddress: '192.168.1.101'
          },
          {
            operationTime: '2025-09-10 08:55:03',
            operatorName: '王五',
            operationType: 'DELETE',
            entityName: '权限',
            description: '删除过期权限',
            ipAddress: '192.168.1.102'
          },
          {
            operationTime: '2025-09-09 16:30:45',
            operatorName: '赵六',
            operationType: 'UPDATE',
            entityName: '用户',
            description: '修改用户密码',
            ipAddress: '192.168.1.103'
          },
          {
            operationTime: '2025-09-09 15:12:29',
            operatorName: '钱七',
            operationType: 'INSERT',
            entityName: '用户',
            description: '创建新用户',
            ipAddress: '192.168.1.104'
          }
        ]
        
        // 渲染图表
        await nextTick()
        renderCharts()
        
      } catch (error) {
        console.error('加载仪表盘数据失败:', error)
        ElMessage.error('加载数据失败，请稍后重试')
      }
    }
    
    // 渲染图表
    const renderCharts = () => {
      // 用户增长趋势图
      if (userGrowthChart.value && !userGrowthChartInstance) {
        userGrowthChartInstance = echarts.init(userGrowthChart.value)
        
        const userGrowthOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          legend: {
            data: ['用户增长', '活跃用户']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '用户增长',
              type: 'line',
              stack: '总量',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: [12, 19, 30, 28, 40, 45, 52, 60, 78],
              smooth: true,
              lineStyle: {
                color: '#409eff'
              }
            },
            {
              name: '活跃用户',
              type: 'line',
              stack: '总量',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: [8, 15, 20, 22, 30, 35, 40, 45, 55],
              smooth: true,
              lineStyle: {
                color: '#67c23a'
              }
            }
          ]
        }
        
        userGrowthChartInstance.setOption(userGrowthOption)
      }
      
      // 操作类型分布图
      if (operationTypeChart.value && !operationTypeChartInstance) {
        operationTypeChartInstance = echarts.init(operationTypeChart.value)
        
        const operationTypeOption = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 10,
            data: ['查询', '新增', '更新', '删除', '其他']
          },
          series: [
            {
              name: '操作类型',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                {
                  value: 45,
                  name: '查询',
                  itemStyle: { color: '#409eff' }
                },
                {
                  value: 25,
                  name: '新增',
                  itemStyle: { color: '#67c23a' }
                },
                {
                  value: 20,
                  name: '更新',
                  itemStyle: { color: '#e6a23c' }
                },
                {
                  value: 8,
                  name: '删除',
                  itemStyle: { color: '#f56c6c' }
                },
                {
                  value: 2,
                  name: '其他',
                  itemStyle: { color: '#909399' }
                }
              ]
            }
          ]
        }
        
        operationTypeChartInstance.setOption(operationTypeOption)
      }
    }
    
    // 监听窗口大小变化，重新渲染图表
    const handleResize = () => {
      if (userGrowthChartInstance) {
        userGrowthChartInstance.resize()
      }
      if (operationTypeChartInstance) {
        operationTypeChartInstance.resize()
      }
    }
    
    onMounted(() => {
      // 设置默认日期范围为最近30天
      const endDate = new Date()
      const startDate = new Date()
      startDate.setDate(startDate.getDate() - 30)
      dateRange.value = [startDate, endDate]
      
      // 加载数据
      loadDashboardData()
      
      // 添加窗口大小变化监听
      window.addEventListener('resize', handleResize)
    })
    
    onUnmounted(() => {
      // 销毁图表实例
      if (userGrowthChartInstance) {
        userGrowthChartInstance.dispose()
      }
      if (operationTypeChartInstance) {
        operationTypeChartInstance.dispose()
      }
      
      // 移除窗口大小变化监听
      window.removeEventListener('resize', handleResize)
    })
    
    return {
      dateRange,
      stats,
      recentOperations,
      userGrowthChart,
      operationTypeChart,
      handleDateRangeChange,
      refreshData,
      viewAllOperations,
      getOperationTypeTag
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.dashboard-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.date-picker {
  width: 300px;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-change {
  font-size: 12px;
}

.stat-change.positive {
  color: #67c23a;
}

.stat-change.negative {
  color: #f56c6c;
}

.change-label {
  margin-left: 4px;
  color: #909399;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.user-icon {
  background-color: #ecf5ff;
  color: #409eff;
}

.role-icon {
  background-color: #f0f9ff;
  color: #13c2c2;
}

.permission-icon {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.operation-icon {
  background-color: #f0f2f5;
  color: #606266;
}

/* 图表区域样式 */
.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card {
  transition: all 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-content {
  padding: 20px;
}

.chart {
  height: 300px;
}

/* 最近操作记录样式 */
.recent-operations-card {
  transition: all 0.3s ease;
}

.recent-operations-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .date-picker {
    width: 100%;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
}
</style>